/**
 * 公用页面模块
 */

var log = require("../lib/log");
var config = require('../config');
var User = require('../models/user');
var crypto = require('crypto');
var RUtil = require('./rutil');

/**
 * JSONP-用户登录
 */
exports.login = function(request, response) {
	var uname = request.query.uname || request.body.uname;
	User.findUName(uname, function(results) {
		log.info("JSONP-登录用户信息：\n" + require('util').inspect(results));

		if(results.length <= 0) {
			// 用户不存在
			response.jsonp({
				'success': false,
				'errMsg': '用户不存在！'
			});
		} else {
			var tmpUser = results[0];
			var upasswd = request.query.upasswd || request.body.upasswd;
			upasswd = crypto.createHash('md5').update(upasswd).digest('hex');
			if(tmpUser.passwd === upasswd) {
				// 用户登录正常
				response.jsonp({
					'success': true,
				});
			} else {
				// 用户密码错误
				response.jsonp({
					'success': false,
					'errMsg': '登录密码错误！'
				});
			}
		}
	});
};

/**
 * JSONP-增加用户
 */
exports.userCreate = function(request, response) {
	var uname = request.query.uname || request.body.uname;
	var upasswd = request.query.upasswd || request.body.upasswd;
	upasswd = crypto.createHash('md5').update(upasswd).digest('hex');

	var uemail = request.query.uemail || request.body.uemail;
	if(!uemail) {
		uemail = uname + "@gmail.com";
	}

	User.insert(uname, upasswd, uemail, function(results) {
		log.info("JSONP-新增用户成功：\n" + require('util').inspect(results));
		response.jsonp({
			'success': true,
			'id': results.insertId,
			'uname': uname,
			'upasswd': upasswd,
			'uemail': uemail
		});
	});
};

/**
 * JSONP-修改用户
 */
exports.userUpdate = function(request, response) {
	var uname = request.query.uname || request.body.uname;
	User.findUName(uname, function(results) {
		log.info("JSONP-查询用户信息：\n" + require('util').inspect(results));

		if(results.length <= 0) {
			// 用户不存在
			response.jsonp({
				'success': false,
				'uname': uname,
				'errMsg': '用户不存在！'
			});
		} else {
			var tmpUser = results[0];
			var id = tmpUser.id;
			
			var upasswd = request.query.upasswd || request.body.upasswd;
			if(!upasswd) {
				upasswd = tmpUser.passwd
			} else {
				upasswd = crypto.createHash('md5').update(upasswd).digest('hex');
			}

			var uemail = request.query.uemail || request.body.uemail;
			if(!uemail) {
				uemail = tmpUser.uemail
			}

			// 更新用户
			User.update(id, uname, upasswd, uemail, function(results) {
				log.info("JSONP-更新用户成功：\n" + require('util').inspect(results));
				response.jsonp({
					'success': true,
					'id': tmpUser.id,
					'uname': uname,
					'upasswd': upasswd,
					'uemail': uemail
				});
			});
		}
	});
};
